/*
 * @Author: yxfan
 * @Date: 2024-06-04 19:29:13
 * @LastEditTime: 2024-06-04 19:54:45
 * @FilePath: /umi-demo/src/pages/demo/KeepAlive/KeepAlive.jsx
 * @Description:
 */
import React, { Component, createContext } from 'react';

const { Provider, Consumer } = createContext();
const withScope = (WrappedComponent) => (props) =>
    (
        <Consumer>
            {(keep) => <WrappedComponent {...props} keep={keep} />}
        </Consumer>
    );

export class AliveScope extends Component {
    nodes = {};
    state = {};

    keep = (id, children) => {
        return new Promise((resolve) =>
            this.setState(
                {
                    [id]: { id, children },
                },
                () => resolve(this.nodes[id]),
            ),
        );
    };

    render() {
        console.log('this.state: ', this.state);
        return (
            <Provider value={this.keep}>
                {this.props.children}
                {Object.values(this.state).map(({ id, children }) => (
                    <div
                        key={id}
                        ref={(node) => {
                            this.nodes[id] = node;
                        }}
                        className="keep-alive-node"
                    >
                        {children}
                    </div>
                ))}
            </Provider>
        );
    }
}

@withScope
class KeepAlive extends Component {
    constructor(props) {
        super(props);
        this.init(props);
    }

    init = async ({ id, children, keep }) => {
        const realContent = await keep(id, children);

        this.placeholder.appendChild(realContent);
    };

    render() {
        return (
            <div
                className="keep-alive-container"
                ref={(node) => {
                    this.placeholder = node;
                }}
            ></div>
        );
    }
}

export default KeepAlive;
